package com.alliky.core.base

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.ExperimentalPagingApi
import com.alliky.core.data.DataRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch


/**
 * ================================================
 * @Description: 描述
 * @Author: wxianing
 * @Date: 2022/11/4 9:47
 * ================================================
 */
@ExperimentalPagingApi
open class BaseViewModel : ViewModel() {

//    val repo: DataRepository = DataRepository()

    //Loading
    val loadingLiveData = SingleLiveData<Boolean>()

    //错误回调
    val errorLiveData = SingleLiveData<Throwable>()

    suspend fun launch(
        block: suspend () -> Unit,
        error: suspend (Throwable) -> Unit,
        complete: suspend () -> Unit
    ) {
        loadingLiveData.postValue(true)
        viewModelScope.launch(Dispatchers.IO) {
            try {
                block()
            } catch (e: Exception) {
                error(e)
            } finally {
                complete()
            }
        }
    }

    override fun onCleared() {
        super.onCleared()
        //viewmodel销毁时调用，可以做一些释放资源的操作
    }
}